package token

import (
	"gitee.com/fierce_wolf/go-fox-edge-common/edgeEntity"
	"github.com/dgrijalva/jwt-go"
	"time"
)

type Claims struct {
	Id  int64
	Pwd string
	jwt.StandardClaims
}

var jwtKey = []byte("aasdasdasifhueuiwyusrfewbfjsdafjk") //证书签名秘钥，用来签发证书

func CreateToken(user *edgeEntity.UserEntity) (string, error) {
	//设置token过期时间(此处设置30天后过期)
	expirationTime := time.Now().Add(30 * 24 * time.Hour)
	claims := &Claims{
		Id:  user.BaseEntity.Id,
		Pwd: user.PassWord,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: expirationTime.Unix(), //过期事件
			IssuedAt:  time.Now().Unix(),     //发布时间
			Subject:   "Fox-Edge",            //主题
			Issuer:    "www.fox-tech.cn",     //发布者
		},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) //生成token
	return token.SignedString(jwtKey)
}

func ParseToken(tokenStr string) (*jwt.Token, *Claims, error) {
	claims := &Claims{}
	token, err := jwt.ParseWithClaims(tokenStr, claims, func(token *jwt.Token) (i interface{}, err error) {
		return jwtKey, nil
	})
	return token, claims, err
}
